//
package geecache

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
)

// PeerGetter 使
type PeerGetter interface {
	Get(group string, key string) (ByteView, bool)
}

type PeerPicker interface {
	PickPeer(key string) (peer PeerGetter, ok bool)
}

type HttpPeerGetter struct {
	service string
	port    int
}


func NewHttpPeerGetter(service string, port int) HttpPeerGetter {
	return HttpPeerGetter{service: service, port: port}
}

func (hp HttpPeerGetter) getService() string {
	return hp.service
}

func (hp HttpPeerGetter) getPort() int {
	return hp.port
}

//Get 从远程节点获取内容
func (hp HttpPeerGetter) Get(group string, key string) (ByteView, bool) {
	if hp.service == "" || hp.port == 0 {
		return ByteView{}, false
	}
	if group == "" || key == "" {
		log.Printf("group和key不能为空\n")
		return ByteView{}, false
	}
	queryUrl := hp.buildUrl(group, key)
	resp, err := http.Get(queryUrl)
	if err != nil {
		log.Printf("访问远程接口出现错误:\n%s\n", err)
		return ByteView{}, false
	}
	defer resp.Body.Close()
	content, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Printf("读取返回结果失败\n%s\n", err)
		return ByteView{}, false
	}
	return ByteView{content}, true
}

func (hp HttpPeerGetter) buildUrl(group string, key string) string {
	return fmt.Sprintf("http://%v:%d%v%v/%v", hp.service, hp.port,
		DEFAULT_PATH_PREFIX, url.PathEscape(group), url.PathEscape(key))
}
